package erp

import (
	"bytes"
	"encoding/json"
	"io"
	"net/http"
	"net/url"

	"mall/service/backend/api/internal/logic/backend/erp"
	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/backend/api/internal/utils/erpurlparse"

	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/rest/httpx"
)

// 订单发货通知
func NewErpDeliverGoodsCallbackHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		ctx := r.Context()
		resp := &types.ErpCallbackResp{
			Success:  false,
			ErrorMsg: "fail",
		}

		defer r.Body.Close()
		var buffer bytes.Buffer
		_, err := io.Copy(&buffer, r.Body)
		if err != nil {
			logx.Errorw("[ERP DeliverGoodsCallback] Error reading response:", logx.Field("detail", err.Error()))
			httpx.OkJsonCtx(ctx, w, resp)
			return
		}

		logx.Infof("DeliverGoodsCallbackHandler : %+v ", buffer.String())
		// app_key=T3087752140&data={"trade_id":"O20241016162030046532002","delivery_code":"YUNDA","delivery_name":"韵达快递","waybill":"123456777","shop_nick":"shop1820","packages":"[{\"deliveryName\":\"韵达快递\",\"deliveryCode\":\"YUNDA\",\"wayBill\":\"123456777\"}]"}&format=json&sign=C02A4567E78309037816D7D81FCC5D0B&timestamp=1734350032157

		str, err := url.QueryUnescape(buffer.String())
		// str := erpurlparse.ParseAsciiToString(string(buffer.Bytes()))
		if err != nil {
			logx.Errorw("[ERP DeliverGoodsCallback] Error url.QueryUnescape:", logx.Field("detail", err.Error()))
			httpx.OkJsonCtx(ctx, w, resp)
			return
		}

		logx.Infof("DeliverGoodsCallbackHandler url.QueryUnescape: %+v ", str)

		data, ok := erpurlparse.Parse(str, svcCtx.Config.Erp.AppKey, svcCtx.Config.Erp.Secret)
		if !ok {
			httpx.OkJsonCtx(ctx, w, resp)
			return
		}

		logx.Infof("DeliverGoodsCallbackHandler data : %+v ", data)

		var req types.DeliverGoodsCallbackReq
		if err = json.Unmarshal([]byte(data), &req); err != nil {
			logx.Errorw("[ERP DeliverGoodsCallback] Error json.Unmarshal:", logx.Field("detail", err.Error()))
			httpx.OkJsonCtx(ctx, w, resp)
			return
		}

		logx.Infof("DeliverGoodsCallbackHandler req : %+v ", req)

		l := erp.NewDeliverGoodsCallbackLogic(ctx, svcCtx)
		ret, err := l.DeliverGoodsCallback(&req)
		if err != nil {
			logx.Errorw("[ERP DeliverGoodsCallback] Error:", logx.Field("detail", err.Error()))
		}
		httpx.OkJsonCtx(ctx, w, ret)
	}
}
